﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices.AccountManagement;
using System.Text;
using MSCaptcha;
using TFSAdministrationTool;

namespace Hydra.Web.Account
{
    public partial class Register : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
        }

        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
            var firstName = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("FirstName");
            var lastName = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("LastName");

            RegisterUser.UserName = firstName.Text + "." + lastName.Text;

            FormsAuthentication.SetAuthCookie(RegisterUser.UserName, true);

            var principalContext = new PrincipalContext(ContextType.Machine, Environment.MachineName);
            var existingUser = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, RegisterUser.UserName);
            var newUser = new UserPrincipal(principalContext, RegisterUser.UserName, RegisterUser.Password, true);

            newUser.Save();
 
            string continueUrl = RegisterUser.ContinueDestinationPageUrl;

            if (String.IsNullOrEmpty(continueUrl))
            {
                continueUrl = "~/";
            }

            Response.Redirect(continueUrl);
        }

        protected void CheckName()
        {
            var firstName = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("FirstName");
            var lastName = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("LastName");
            var userName = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("UserName");
            var email = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("Email");

            if (!(string.IsNullOrWhiteSpace(firstName.Text) || string.IsNullOrWhiteSpace(lastName.Text)))
            {
                userName.Text = firstName.Text + "." + lastName.Text;

                var script = new StringBuilder();

                script.AppendLine("<script language='javascript'>");
                script.AppendLine("document.getElementById('" + email.ClientID + "').focus();");
                script.AppendLine("</script>");

                if (!ClientScript.IsStartupScriptRegistered("EmailNameFocus"))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "EmailNameFocus", script.ToString());
                }
            } 
            else if (!string.IsNullOrWhiteSpace(firstName.Text))
            {
                var script = new StringBuilder();

                script.AppendLine("<script language='javascript'>");
                script.AppendLine("document.getElementById('" + lastName.ClientID + "').focus();");
                script.AppendLine("</script>");

                if (!ClientScript.IsStartupScriptRegistered("LastNameFocus"))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "LastNameFocus", script.ToString());
                }
            }
        }

        protected void LastNameChanged(object sender, EventArgs e)
        {
            CheckName();
        }

        protected void FirstNameChanged(object sender, EventArgs e)
        {
            CheckName();
        }

        protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
        {
            var userName = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("UserName");
            var principalContext = new PrincipalContext(ContextType.Machine, Environment.MachineName);
            var existingUser = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, Environment.MachineName + "\\" + userName.Text);
            var errorMessage = (Label)RegisterUserWizardStep.ContentTemplateContainer.FindControl("ErrorMessage");
            var enterCaptcha = (TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("EnterCaptcha");
            var captcha = (CaptchaControl)RegisterUserWizardStep.ContentTemplateContainer.FindControl("CaptchaControl");
            var userNameValidator = (CustomValidator)RegisterUserWizardStep.ContentTemplateContainer.FindControl("UserNameValidator");
            var captchValidator = (CustomValidator)RegisterUserWizardStep.ContentTemplateContainer.FindControl("CaptchaValidator");

            if (existingUser != null)
            {
                e.Cancel = true;
                userNameValidator.IsValid = false;
            }
            else 
            {
                captcha.ValidateCaptcha(enterCaptcha.Text);

                if (!captcha.UserValidated)
                {
                    e.Cancel = true;
                    captchValidator.IsValid = false;
                }
            }
        }
    }
}
